<?php

include'Utils.php';

class LibsController extends AppController{
	
	/**
	 * List components used in this class
	 */
	public $components = array('CenterInfo', 'Subject', 'Course');
	
	/**
	 * Front-End function used to display list library page
	 */
	public function index(){
		// Get all subjects
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		// Get common information
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);	
		// Get list Course
		$courses = $this->Course->getAll();
		$this->set('courses', $courses);
		
		$subId = isset($_GET['sub_id']) ? $_GET['sub_id'] : "";
		If($subId != ""){
	
			$totalRec = $this->Lib->find('count', array(
				'conditions' => array('Lib.m_lib_sub_id' => $subId)
			));
			
			$pageNo = isset($_GET['page_no']) ? $_GET['page_no'] : 1;
			$startPage = isset($_GET['start_page']) ? $_GET['start_page'] : 1;
			$endPage = isset($_GET['end_page']) ? $_GET['end_page'] : $startPage + 4;
			$pagerInfo = array();
			$pagerInfo = Utils::getPagerInfo($pageNo, $totalRec, $startPage, $endPage);
			$libList = array();
			$libList = $this->Lib->find('all', array(
				'condition' => array('Lib.m_lib_sub_id' => $subId),
				'order' => 'Lib.m_lib_id ASC',
				'limit' => 5,
				'page' => $pagerInfo['start_index']
			));
			$this->set('listLibs', $libList);
			$this->set('pagerInfo', $pagerInfo);
			$this->set('selectedSubId', $subId);
			
		}
	}
	
	/**
	 * Front-End function used to display list library page
	 */
	public function list_lib(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		// Get all subjects
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		
		// Get common information
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);	
		
		$subId = isset($_GET['sub_id']) ? $_GET['sub_id'] : "";
		If($subId != ""){
	
			$totalRec = $this->Lib->find('count', array(
				'conditions' => array('Lib.m_lib_sub_id' => $subId)
			));
			
			$pageNo = isset($_GET['page_no']) ? $_GET['page_no'] : 1;
			$startPage = isset($_GET['start_page']) ? $_GET['start_page'] : 1;
			$endPage = isset($_GET['end_page']) ? $_GET['end_page'] : $startPage + 4;
			$pagerInfo = array();
			$pagerInfo = Utils::getPagerInfo($pageNo, $totalRec, $startPage, $endPage);
			$libList = array();
			$libList = $this->Lib->find('all', array(
				'condition' => array('Lib.m_lib_sub_id' => $subId),
				'order' => 'Lib.m_lib_id ASC',
				'limit' => 5,
				'page' => $pagerInfo['start_index']
			));
			
			$this->set('listLibs', $libList);
			$this->set('pagerInfo', $pagerInfo);
			$this->set('selectedSubId', $subId);
			
			$subName =  $_GET['sub_name'];
			$this->set('selectedSubName', $subName);
			
		}
	}
	
	public function edit(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		// Get common information
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);	
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		
		if (!isset($_POST['libId'])){
			$this->redirect(array('action' => 'list_lib'));
		}
		
		$libId = $_POST['libId'];
		$lib = $this->Lib->findBym_lib_id($libId);
		$this->set('libId', $libId);
		
		if (isset($_POST['isBack'])){
			if (isset($_POST['libTempFile'])){
				unlink("temp/upload_temp/".$_POST['libFileName']);
			}
		}
		
		$subId = (isset($_POST['subId'])) ? $_POST['subId'] : "";
		$subName = (isset($_POST['subName'])) ? $_POST['subName'] : "";
		
		$this->set('subId', $subId);
		$this->set('subName', $subName);
		
		$libTitle = (isset($_POST['libTitle'])) ? $_POST['libTitle'] : $lib['Lib']['m_lib_title'];
		$libDesc = (isset($_POST['libDesc'])) ? $_POST['libDesc'] : $lib['Lib']['m_lib_descript'];
		$libFileName = $lib['Lib']['m_file_name'];
		
		$this->set('libTitle', $libTitle);
		$this->set('libDesc', $libDesc);
		$this->set('libFileName', $libFileName);
	}
	
	public function addLib(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		// Get common information
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);	
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		
		if (isset($_POST['isBack'])){
			if (isset($_POST['libTempFile'])){
				unlink("temp/upload_temp/".$_POST['libFileName']);
			}
		}
		
		$subId = (isset($_POST['subId'])) ? $_POST['subId'] : "";
		$subName = (isset($_POST['subName'])) ? $_POST['subName'] : "";
		
		$this->set('subId', $subId);
		$this->set('subName', $subName);
		
		$libTitle = (isset($_POST['libTitle'])) ? $_POST['libTitle'] : "";
		$libDesc = (isset($_POST['libDesc'])) ? $_POST['libDesc'] : "";
		
		$this->set('libTitle', $libTitle);
		$this->set('libDesc', $libDesc);
	}
	
	public function libDelete(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		
		if (isset($_POST["libId"])){
			$libIds = explode ("," , $_POST["libId"]);
			
			foreach ($libIds as $lib_id):	
				$lib = $this->Lib->findBym_lib_id($lib_id);					
				if ($this->Lib->deleteAll(array('Lib.m_lib_id' => $lib_id), false)) {
					if ($lib['Lib']['m_file_name'] != NULL)
						unlink("sub_libs/" . $_POST["subId"] . "/" . $lib['Lib']['m_file_name']);
					}
			endforeach;
		}
		$this->redirect(array('action' => 'list_lib?sub_id='.$_POST["subId"].'&sub_name='.$_POST['subName']));
	}
	
	/**
	 * Confirm
	 */
	function confirmLib(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		// Get common information
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		
		//Get POST data and display on page
		if(isset($_POST['libId'])){
			$this->set('libId', $_POST["libId"]);
		}
		
		$this->set('subId', isset($_POST["subId"]) ? $_POST["subId"] : "");
		$this->set('subName', isset($_POST['subName']) ? $_POST['subName'] : "");
		$this->set('libTitle',  isset($_POST["libTitle"]) ? $_POST["libTitle"] : "");
		$this->set('libDescript', isset($_POST["libDescript"]) ? htmlentities($_POST["libDescript"], ENT_QUOTES, 'utf-8') : "");
		
		if (isset($_POST["libOldFile"])){
			$this->set('libOldFile', $_POST["libOldFile"]);
			}
			
		/* FILE */
		if (!isset($_FILES["file"])){
			$this->set('libFileName', $_POST["libFileName"]);
			return;
		}
		
		if ($_FILES["file"]["error"] > 0) {
			echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
		} else {
			$this->set('libTempFile', $_FILES["file"]["tmp_name"]);
			$this->set('libFileName', $_FILES["file"]["name"]);
			move_uploaded_file($_FILES["file"]["tmp_name"],
			"temp/upload_temp/" .$_FILES["file"]["name"]);
		}
	}
	
	function libRegist(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		if($this->request->is('post')){
			if(isset($_POST['libId'])){
				if(!isset($_POST["libTitle"]) || !isset($_POST['libFileName']) || !isset($_POST['libDesc'])){
					$this->redirect(array('action' => "list_lib"));
				}
				$dataNeedToSave = array('Lib.m_lib_title' => "'".$_POST["libTitle"]."'",
						                'Lib.m_file_name' => "'".$_POST['libFileName']."'",
						                'Lib.m_lib_descript' => "'".htmlentities($_POST['libDesc'], ENT_QUOTES, 'utf-8')."'");
				$saveCondition = array('Lib.m_lib_id' => $_POST['libId']);
				
				if (isset($_POST['libTempFile'])){
					/* Delete old file */
					if ((isset($_POST['libOldFile'])) && (strlen($_POST['libOldFile']) > 0))
						unlink("sub_libs/" . $_POST["subId"] . "/" .$_POST['libOldFile']);
					
					copy("temp/upload_temp/".$_POST['libFileName'],
						"sub_libs/" . $_POST["subId"] . "/" .$_POST['libFileName']);
					unlink("temp/upload_temp/".$_POST['libFileName']);
					}
					
				if ($this->Lib->updateAll($dataNeedToSave, $saveCondition)) {
					$this->redirect(array('action' => 'list_lib?sub_id='.$_POST["subId"].'&sub_name='.$_POST['subName']));
				}
			}else{
				$this->Lib->create();
				$dataNeedToSave = array('Lib' => array('m_lib_title' => $_POST['libTitle'],
						                'm_file_name' => $_POST['libFileName'],
						                'm_lib_descript' => htmlentities($_POST['libDesc'], ENT_QUOTES, 'utf-8'),
						                'm_lib_sub_id' => $_POST['subId']));
				
				if($this->Lib->save($dataNeedToSave)){
					if (isset($_POST['libTempFile'])){
						copy("temp/upload_temp/".$_POST['libFileName'],
						"sub_libs/" . $_POST["subId"] . "/" .$_POST['libFileName']);
						unlink("temp/upload_temp/".$_POST['libFileName']);
					}
					$this->redirect(array('action' => 'list_lib?sub_id='.$_POST["subId"].'&sub_name='.$_POST['subName']));
				}
			}
		}
	}
	
	/**
	 * Front-End function used to download file
	 */
	public function download(){
		// Get file name using file id
		$id = $_GET['id'];
		$libList = $this->Lib->findAllBym_lib_id($id);
		$filename = $libList[0]['Lib']['m_file_name']; // of course find the exact filename....      
		
		// Set header information
		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Cache-Control: private', false); // required for certain browsers 
		header('Content-Type: application/octet-stream');
		
		header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
		header('Content-Transfer-Encoding: binary');
		header('Content-Length: ' . filesize($filename));
		
		// Read file
		readfile($filename);
	}
	
	/**
	 * 
	 * Function used to check if file existed???
	 * @param String $imageName
	 */
	public function checkFileExist(){
		$fileName = $_POST['libFileName'];
		
		/* Move image of this faculty to delete_temp before checking
		 * In order to allow user post same image file name for this faculty
		 */
		if ((isset($_POST['libOldFile'])) && (strlen($_POST['libOldFile']))){
			copy("sub_libs/" . $_POST["subId"] . "/" . $_POST['libOldFile'],
			 	"temp/delete_temp/".$_POST['libOldFile']);
			unlink("sub_libs/" . $_POST["subId"] . "/" .$_POST['libOldFile']);
		}
		
		$fileError = false;
		if (file_exists("sub_libs/" . $_POST["subId"] . "/" . $fileName)){
			$fileError = true;
		}
		
		if ((isset($_POST['libOldFile'])) && (strlen($_POST['libOldFile']))){
			copy("temp/delete_temp/".$_POST['libOldFile'], "sub_libs/"  . $_POST["subId"] . "/" .$_POST['libOldFile']);
			unlink("temp/delete_temp/".$_POST['libOldFile']);
		}
		
		if ($fileError == true){
			echo "File ".$fileName." đã tồn tại";die;
		}else{
			echo ""; die;
		}
	}
	
}
?>